package cn.maihe.elg.operation.common.validator;

import cn.maihe.elg.operation.common.annotation.DateFmt;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @Description
 * @Author WJH
 * @Date 2021/07/13
 */
public class DateFmtValidator implements ConstraintValidator<DateFmt, String> {
    private String fmtPatten;

    @Override
    public void initialize(DateFmt constraintAnnotation) {
        this.fmtPatten = constraintAnnotation.value();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        boolean valid;
        if (StringUtils.isNotBlank(value)) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat(fmtPatten);
                sdf.setLenient(false);
                sdf.parse(value);
                valid = true;
            } catch (ParseException e) {
                valid = false;
            }
        } else {
            valid = true;
        }
        return valid;
    }

    public static void main(String[] args) {
        try {
            String a = "yyyy-MM-dd HH:mm:ss";
            String v = "1976-01-12 12:12:12";
            LocalDateTime.parse(v, DateTimeFormatter.ofPattern(a));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
